<!DOCTYPE html>
<html>
	<head>
		<title>数据录入</title>
		<meta charset="utf-8">
		<meta name="viewport"
			content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<!-- 所有的 css & js 资源 -->
		<link rel="stylesheet" href="../../static/kj/element-ui/theme-chalk/index.css">
		<link rel="stylesheet" href="../../static/sa.css">
		
		<script src="../../static/kj/vue.min.js"></script>
		<script src="../../static/kj/axios.min.js"></script>
		<script src="../../static/kj/element-ui/index.js"></script>
		<script src="../../static/kj/jquery.min.js"></script>
		<script src="../../static/kj/layer/layer.js"></script>

		<script src="../../static/sa.js"></script>
		<script src="../../sa-resources/config.js"></script>

		<style type="text/css">
			.demo-table-expand {
				font-size: 0;
			}

			.demo-table-expand label {
				width: 90px;
				color: #99a9bf;
			}

			.demo-table-expand .el-form-item {
				margin-right: 0;
				margin-bottom: 0;
				width: 100%;
				border-bottom: 1px #eeeeee solid;
			}

			.el-tooltip__popper {
				max-width: 30%
			}

			.wuyan-expand-row {
				margin: 5px 0px;
				line-height: 23px;
				border-bottom: 1px solid #eee;
			}

			.wuyan-expand-row div {
				display: inline-block;
			}

			.wuyan-expand-row .label {
				width: 150px;
				font-weight: bold;
			}

			.wuyan-expand-row .content {
				width: calc(100% - 300px);
			}

			.wuyan-expand-row .content span {
				/* color: #b2b2b2; */
				color: #EE0000;
			}

			.wuyan-expand-row .op {
				width: 100px;
				text-align: center;
				cursor: pointer;
				color: #1890ff;
			}

			.wuyan-expand-row .op:hover {
				color: #EE0000;
			}
		</style>
	</head>
	<body>
		<div class="vue-box" style="display: none;" :style="'display: block;'">
			<div class="c-panel">
				<!-- ------------- 参数栏 ------------- -->
				<div class="c-title">检索参数</div>
				<el-form>
					<div class="c-item">
						<label class="c-label">关键词：</label>
						<el-input size="mini" v-model="queryParams[0].right[0]" placeholder="如数据录入 学校 开放"></el-input>
					</div>
					<div class="c-item">
						<label class="c-label">审核状态：</label>
						<el-select size="mini" v-model="queryParams[1].right[0]" placeholder="请选择">
							<el-option label="全部" value=""></el-option>
							<el-option v-for="(item, index) in cfgStatusArray" :key="index" :label="item.value"
								:value="item.key">
							</el-option>
						</el-select>
					</div>

					<!-- 预定义检索参数 -->
					<div class="c-item" v-for="(item, index) in defaultQueryParams">
						<label class="c-label">{{item.label}}：</label>
						<div style="display: inline-block;" v-if="item.tag == 'el-input-number'">
							<!-- 计数器 -->
							<el-input size="mini" v-model="item.right[0]" placeholder="最小值" style="width: 70px;">
							</el-input>
							<span>-</span>
							<el-input size="mini" v-model="item.right[1]" placeholder="最大值" style="width: 70px;">
							</el-input>
						</div>
						
						<!-- 选择器 -->
						<el-select size="mini" v-model="item.right[0]" v-else-if="item.tag == 'el-select'">
							<el-option v-for="(option, optionIndex) in item.field.__slot__.options" :key="'option-' + optionIndex" :label="option.label" :value="option.value" :disabled="option.disabled"></el-option>
						</el-select>

						<el-input v-else size="mini" v-model="item.right[0]" placeholder=""></el-input>
					</div>

					<div class="c-item" style="min-width: 0px;">
						<el-button size="mini" type="primary" icon="el-icon-search" @click="params.page = 1; f5()">查询
						</el-button>
					</div>
				</el-form>

				<!-- ------------- 快捷按钮 ------------- -->
				<div class="fast-btn">
					<el-button size="mini" type="primary" icon="el-icon-plus" @click="add()">新增</el-button>
					<el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteByIds()">批量删除</el-button>
					<el-button size="mini" type="warning" icon="el-icon-upload" @click="dialogUploadVisible = true">导入
					</el-button>
					<el-button size="mini" type="success" icon="el-icon-download" @click="exportExcel">导出</el-button>
					<el-button size="mini" type="info" icon="el-icon-refresh" @click="sa.f5()">重置</el-button>
				</div>

				<!-- ------------- 数据列表 ------------- -->
				<el-table :data="dataList" size="small" ref="data-table" class="wuyan-table" max-height="600"
					@row-click="handleRowChange" highlight-current-row>
					<el-table-column align="center" type="selection" width="45px"></el-table-column>

					<el-table-column type="index" align="center" label="序号" width="50"></el-table-column>

					<el-table-column v-for="(item, index) in formData.fields" :key="'main-' + index" align="center"
						:width="item.type == 'textarea' ? '200px' : '100px'" :show-overflow-tooltip="true"
						:label="item.__config__.label" :prop="item.__vModel__" v-if="item.__config__.queryMainShow">
						<template slot-scope="s">
							<!-- 附件操作 -->
							<el-button v-if="item.__config__.tag == 'el-upload' && s.row[item.__vModel__]" class="c-btn"
								type="warm" size="mini" @click.stop="showFile(s.row[item.__vModel__])">
								查看附件
							</el-button>
							<!-- 其它 -->
							<span
								v-else>{{s.row[item.__vModel__] instanceof Array ? s.row[item.__vModel__].join(',') : s.row[item.__vModel__]}}</span>
						</template>
					</el-table-column>

					<el-table-column align="center" :formatter="getCfgStatusValue" label="审核状态" prop="cfg_status"
						fixed="right">
					</el-table-column>

					<el-table-column align="center" label="更新时间" prop="operate_time">
						<template slot-scope="s">
							<span>{{timestampToTime(s.row.operate_time)}}</span>
						</template>
					</el-table-column>

					<el-table-column align="center" label="操作" width="240px" fixed="right">
						<template slot-scope="s">
							<el-button v-if="!s.row.cfg_status || s.row.cfg_status=='0' || s.row.cfg_status=='3'"
								class="c-btn" type="success" icon="el-icon-document-checked"
								@click.stop="submit(s.$index, s.row)">
								{{s.row.cfg_status=='3' ? '重新提交' : '提交'}}
							</el-button>

							<el-button v-if="s.row.cfg_status == '4'" class="c-btn" type="success" icon="el-icon-back"
								@click.stop="cancelSubmit(s.$index, s.row)">撤销
							</el-button>

							<el-button v-if="s.row.cfg_status != '1'" class="c-btn" type="primary" icon="el-icon-edit"
								@click.stop="update(s.row)">修改
							</el-button>

							<el-button v-if="s.row.cfg_status != '1'" class="c-btn" type="danger" icon="el-icon-delete"
								@click.stop="del(s.row)">删除
							</el-button>
						</template>
					</el-table-column>

				</el-table>

				<!-- ------------- 分页 ------------- -->
				<div class="page-box">
					<el-pagination background layout="total, prev, pager, next, sizes, jumper"
						:current-page.sync="params.page" :page-size.sync="params.limit" :total="dataCount"
						:page-sizes="[15,30,50,100,500,1000]" @current-change="f5()" @size-change="f5()">
					</el-pagination>
				</div>
			</div>

			<el-dialog :title="formData.name + '(导入)'" :visible.sync="dialogUploadVisible">
				<div style="width: 100%;text-align: center;">
					<el-upload class="upload-demo" drag accept=".xls,.xlsx" :headers="{authorization: authorization}"
						:action="URL_DATA_IMPORT + formData.formRef" :multiple="false" :on-success="importSuccess"
						:on-error="importError">
						<i class="el-icon-upload"></i>
						<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
						<div class="el-upload__tip" slot="tip">单文件大小建议不超过10Mb</div>
					</el-upload>
				</div>
			</el-dialog>

			<!-- 审批的批注 -->
			<el-dialog title="修改数据项" :visible.sync="dialogFieldEditVisible">
				<el-form :model="approvalData" :rules="dialogFieldEditVisible" label-width="150px">
					<el-form-item :label="chooseData.fieldLabel" prop="remark">
						<el-input v-model="approvalData.remark" type="textarea"></el-input>
					</el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button @click="dialogFieldEditVisible = false">取消</el-button>
					<el-button type="primary" @click="saveSubmit">确定</el-button>
				</div>
			</el-dialog>

			<!-- 数据明细 -->
			<el-dialog style="height: 100%;" title="数据明细" :visible.sync="dialogInfoVisible" width="80%" top="10vh"
				@close="dialogInfoClose">
				<div style="height: 600px;overflow-y: auto;">
					<el-row v-if="chooseData.row">
						<el-col v-for="(item, index) in formData.fields" :key="'expand-' + index" :md="24" :lg="24">
							<div class="wuyan-expand-row">
								<div class="label">{{item.__config__.label}}</div>
								<div class="content">
									<el-button
										v-if="item.__config__.tag == 'el-upload' && chooseData.row[item.__vModel__]"
										size="mini" class="c-btn" type="warm"
										@click.stop="showFile(chooseData.row[item.__vModel__])">
										<span style="color: #000000">查看附件</span>
									</el-button>

									<p v-else>
										{{ chooseData.row[item.__vModel__] instanceof Array ? chooseData.row[item.__vModel__].join(',') : chooseData.row[item.__vModel__]}}
									</p>

									<span v-if="checkFieldNotes(chooseData.row, item.__vModel__)">
										批：{{checkFieldNotes(chooseData.row, item.__vModel__)}}
									</span>
								</div>
								<div class="op"
									@click.stop="submit(-1, chooseData.row, item.__vModel__,item.__config__.label)"
									v-if="chooseData.row.cfg_status != '1'">
									<span>修改</span>
								</div>
							</div>
						</el-col>
					</el-row>
				</div>
			</el-dialog>

			<!-- 附件列表 -->
			<el-dialog style="height: 100%;" title="附件列表" :visible.sync="dialogFileVisible" width="80%" top="10vh"
				@close="dialogFileClose">
				<el-card>
					<div v-for="(item, index) in chooseData.files" :key="index" style="margin: 5px;">
						<el-row style="height: 30px;line-height: 30px;">
							<el-col :span="18">
								{{item.name}}
							</el-col>
							<el-col :span="6" style="text-align: right;">
								<el-button size="mini" type="warm" @click.stop="window.open(item.url)">查看</el-button>
							</el-col>
						</el-row>
					</div>
				</el-card>
			</el-dialog>
		</div>

		<script src="../../sa-resources/api.js"></script>
		<script src="../../sa-resources/wuyan.js"></script>
		<script src="../../sa-resources/element-ui-helper.js"></script>

		<script>
			var app = new Vue({
				el: '.vue-box',
				data: {
					authorization: '',
					// 表单ID
					formId: parseInt(sa.p('id', 0)),
					// 数据ID
					dataId: sa.p('dataId', ''),
					// 表单数据
					formData: {
						fields: []
					},
					// 请求参数  
					params: {
						params: '',
						page: 1,
						limit: 15
					},
					// 查询参数
					queryParams: [{
							left: 'cfg_tags',
							op: 'text',
							right: ['']
						},
						{
							left: 'cfg_status',
							op: 'eq',
							right: ['']
						},
						{
							left: 'id',
							op: 'eq',
							right: [sa.p('dataId', '') ? sa.p('dataId', '') : '']
						},
					],
					// 预定义查询参数
					defaultQueryParams: [],
					// 当前数据
					dataList: [],
					// 数据量
					dataCount: 0,
					// 选中参数
					chooseData: {
						row: null,
						field: null,
						fieldLabel: null,
						fieldValue: null,
						index: null,
						files: null
					},
					// 审批信息
					approvalData: {
						formId: 0,
						dataId: '',
						status: 0,
						fieldName: '',
						remark: '',
					},
					cfgStatusArray: [],
					dialogUploadVisible: false,
					dialogFieldEditVisible: false,
					dialogInfoVisible: false,
					dialogFileVisible: false,
				},
				created: function() {
					this.init();
					this.authorization = user.token
				},
				methods: {
					// 初始化
					init() {
						axiosConfig(axios)
						getBaseRoles()

						setTimeout(() => {

							this.cfgStatusArray = this.convertCfgStatus2Array()

							let loading = elLoadding({
								that: this
							})
							let url = getUrl('pub-form', 'getOne', [this.formId])
							let http = getHttp(axios, 'pub-form', 'getOne')
							http(url, {}).then(res => {
								res.fields = JSON.parse(res.fields)
								this.formData = res

								// 预定义检索参数
								this.defaultQueryParams = queryConfig2List(res.fields)
								console.log(this.defaultQueryParams)

								this.queryParams.push({
									left: 'creator_id',
									op: 'eq',
									right: [accountIsRole('inputer-role') ? user.info.id : '']
								})
								this.f5();

								sa.onInputEnter(); // 监听输入框的回车事件，执行查询  
								loading.close();
							}).catch((err) => { // 请求失败处理
								sa.error(err.msg);
								loading.close();
							});
						}, 500)
					},

					// 刷新
					f5: function() {
						let query = this.queryParams.concat(this.defaultQueryParams)
						this.params.params = queryParamsToJsonStr(query)

						let loading = elLoadding({
							that: this
						})

						axios.get('/form/api/' + this.formData.formRef, {
								params: this.params
							})
							.then(res => {
								this.dataList = res.list ? res.list : []; // 数据
								this.dataCount = res.count; // 分页
								sa.f5TableHeight(); // 刷新表格高度 

								loading.close();
							})
							.catch((err) => { // 请求失败处理
								this.$notify.info({
									title: '消息',
									message: '初始化数据失败'
								});

								loading.close();
							});
					},

					// 初始化审批数据
					createApprovalData() {
						this.approvalData = {
							formId: 0,
							dataId: '',
							status: 0,
							fieldName: '',
							remark: '',
						}
					},

					// 提交
					submit(index, data, fieldName, fieldLabel) {
						this.chooseData.row = data
						this.chooseData.index = index

						this.approvalData.dataId = data.id
						this.approvalData.formId = this.formData.id

						// 如果fieldName存在，则代表字段型修改
						if (fieldName) {
							this.approvalData.fieldName = fieldName
							this.approvalData.remark = data[fieldName]

							this.chooseData.field = fieldName
							this.chooseData.fieldLabel = fieldLabel

							this.dialogFieldEditVisible = true
						} else {
							this.approvalData.remark = ''
							this.approvalData.fieldName = ''
							this.saveSubmit()
						}
					},

					// 保存结果
					saveSubmit() {
						let loading = elLoadding({
							that: this
						})

						let url = getUrl('psoa-approval', 'data-re-submit')
						let http = getHttp(axios, 'psoa-approval', 'data-re-submit')
						http(url, this.approvalData).then(res => {
							this.dialogFieldEditVisible = false

							// 对于字段型修改和整体提交需要分别判断
							if (this.chooseData.field) {
								this.chooseData.row[this.chooseData.field] = this.approvalData.remark
							} else {
								this.chooseData.row['cfg_status'] = '4'
							}

							this.createApprovalData()
							sa.ok('操作已提交')
							this.f5()

							loading.close();
						}).catch((err) => { // 请求失败处理
							sa.error(err.msg);
							loading.close();
						});
					},

					// 撤销
					cancelSubmit(index, data) {
						let loading = elLoadding({
							that: this
						})

						data.cfg_status = '0'

						let url = getUrl('form-data', 'edit', {
							form: this.formData.formRef,
							id: data.id
						})
						let http = getHttp(axios, 'form-data', 'edit')
						http(url, {
							cfg_status: data.cfg_status
						}).then(res => {
							this.$set(this.dataList, index, data)

							sa.ok('已撤销')
							loading.close();
						}).catch((err) => { // 请求失败处理
							sa.error(err.msg);
							loading.close();
						});
					},

					// 新增数据
					add() {
						sa_admin.showTab({
							id: 'form-data-' + this.formData.id,
							name: this.formData.name + '(新增数据)',
							url: getFormUrl({
								path: 'index.html',
								params: 'id=' + this.formData.id + '&op=run&tab=form-data-' + this
									.formData.id,
								position: '/show'
							})
						});
					},

					// 导入成功的回调
					importSuccess(res, file, fileList) {
						if (res.code == RES_CODE_SUCCESS) {
							sa.ok('导入成功');
							this.dialogUploadVisible = false
							this.f5()
						} else {
							sa.error(res.msg);
						}
					},

					// 导入失败
					importError(err, file, fileList) {
						sa.error(err.msg);
					},

					// 导出数据
					exportExcel() {
						let loading = elLoadding({
							that: this
						})

						this.params.params = queryParamsToJsonStr(this.queryParams)

						let url = URL_DATA_EXPORT + this.formData.formRef + '?'
						for (let key in this.params) {
							url += key + '=' + this.params[key] + '&'
						}

						window.open(url)
					},

					// 修改
					update: function(data) {
						sa_admin.showTab({
							id: 'form-data-update-' + data.id.toString().replace('.', '-'),
							name: '修改数据(' + data.id.toString().replace('.', '-') + ')',
							url: getFormUrl({
								path: 'index.html',
								params: 'id=' + this.formData.id + '&dataId=' + data.id +
									'&op=run&tab=form-data-update-' + data.id,
								position: '/show'
							})
						});
					},

					// 删除
					del: function(data) {
						sa.confirm('是否删除，此操作不可撤销', function() {
							let loading = elLoadding({
								that: this
							})

							axios.delete('/form/api/' + this.formData.formRef + '/' + data.id)
								.then(res => {
									this.f5()
									sa.ok('删除成功');

									loading.close()
								})
								.catch(function(err) { // 请求失败处理
									this.$notify.info({
										title: '消息',
										message: '操作失败'
									});

									loading.close()
								});
						}.bind(this));
					},

					// 批量删除
					deleteByIds: function() {
						// 获取选中元素的id列表
						let selection = this.$refs['data-table'].selection;
						let ids = sa.getArrayField(selection, 'id');
						if (selection.length == 0) {
							return sa.msg('请至少选择一条数据')
						}

						// 提交删除 
						sa.confirm('是否删除，此操作不可撤销', function() {
							let loading = elLoadding({
								that: this
							})

							axios.delete('/form/api/' + this.formData.formRef + '/' + ids.toString())
								.then(res => {
									this.f5()
									sa.ok('删除成功');

									loading.close()
								})
								.catch(function(err) { // 请求失败处理
									this.$notify.info({
										title: '消息',
										message: '操作失败'
									});

									loading.close()
								});
						}.bind(this));
					},

					// 获取状态标识的含义
					getCfgStatusValue: function(data, column) {
						let res = baseConfig.formData.cfgStatus[data['cfg_status']]
						return res ? res : '未提交'
					},

					// 行单击事件
					handleRowChange(row, event, column) {
						this.dialogInfoVisible = true
						this.chooseData.row = row
					},

					// 关闭
					dialogInfoClose() {
						this.dialogInfoVisible = false
					},

					// 将json格式的配置转化为数组
					convertCfgStatus2Array() {
						let res = []
						for (let key in baseConfig.formData.cfgStatus) {
							let item = {
								key: key,
								value: baseConfig.formData.cfgStatus[key]
							}
							res.push(item)
						}

						return res
					},

					// 校验字段是否已有批注
					checkFieldNotes(row, field) {
						return row['cfg_' + field + '_notes']
					},

					// 展示附件
					showFile(files) {
						this.chooseData.files = files
						this.dialogFileVisible = true
					},

					dialogFileClose() {
						this.dialogFileVisible = false
					},
				}
			})
		</script>
	</body>
</html>
